<?php

namespace app\controller;

use think\Request;
use app\model\Category as CategoryModel;
use app\model\UserLog;
use Exception;

class Category
{
    /**
     * 获取分类列表
     */
    public function index(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $categories = CategoryModel::getUserCategories($userId);

            return success($categories, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取系统分类模板
     */
    public function templates(Request $request)
    {
        try {
            $categories = CategoryModel::getSystemCategories();

            return success($categories, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 创建分类
     */
    public function save(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $data = $request->only(['name', 'icon', 'color', 'description']);

            // 验证必填字段
            if (empty($data['name'])) {
                return error('分类名称不能为空');
            }

            // 检查名称是否重复
            if (CategoryModel::checkNameExists($data['name'], $userId)) {
                return error('分类名称已存在');
            }

            // 获取排序值
            $sort = CategoryModel::getMaxSort($userId) + 1;

            $categoryData = [
                'user_id' => $userId,
                'name' => $data['name'],
                'icon' => $data['icon'] ?? '',
                'color' => $data['color'] ?? '',
                'description' => $data['description'] ?? '',
                'sort' => $sort,
                'is_system' => 0,
                'is_active' => 1,
            ];

            $category = CategoryModel::create($categoryData);

            // 记录日志
            UserLog::record($userId, 'create_category', "创建分类: {$category->name}", 'category', $category->id);

            return success($category, '创建成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 更新分类
     */
    public function update(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $categoryId = $request->param('id');
            $data = $request->only(['name', 'icon', 'color', 'description']);

            if (empty($categoryId)) {
                return error('分类ID不能为空');
            }

            if (empty($data['name'])) {
                return error('分类名称不能为空');
            }

            $category = CategoryModel::where('id', $categoryId)
                ->where('user_id', $userId)
                ->where('is_system', 0)
                ->find();

            if (!$category) {
                return error('分类不存在或不能修改');
            }

            // 检查名称是否重复
            if (CategoryModel::checkNameExists($data['name'], $userId, $categoryId)) {
                return error('分类名称已存在');
            }

            // 更新分类
            $updateData = [];
            foreach (['name', 'icon', 'color', 'description'] as $field) {
                if (isset($data[$field])) {
                    $updateData[$field] = $data[$field];
                }
            }

            $category->save($updateData);

            // 记录日志
            UserLog::record($userId, 'update_category', "更新分类: {$category->name}", 'category', $category->id);

            return success($category, '更新成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 删除分类
     */
    public function delete(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $categoryId = $request->param('id');

            if (empty($categoryId)) {
                return error('分类ID不能为空');
            }

            $category = CategoryModel::where('id', $categoryId)
                ->where('user_id', $userId)
                ->where('is_system', 0)
                ->find();

            if (!$category) {
                return error('分类不存在或不能删除');
            }

            // 检查是否有账号使用该分类
            $accountCount = $category->account_count;
            if ($accountCount > 0) {
                return error("该分类下还有{$accountCount}个账号，请先移动或删除账号");
            }

            $categoryName = $category->name;
            $category->delete();

            // 记录日志
            UserLog::record($userId, 'delete_category', "删除分类: {$categoryName}", 'category', $categoryId);

            return success(null, '删除成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 分类排序
     */
    public function sort(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $sorts = $request->param('sorts'); // [{'id': 1, 'sort': 1}, ...]

            if (empty($sorts) || !is_array($sorts)) {
                return error('排序数据不能为空');
            }

            foreach ($sorts as $item) {
                if (!isset($item['id']) || !isset($item['sort'])) {
                    continue;
                }

                CategoryModel::where('id', $item['id'])
                    ->where('user_id', $userId)
                    ->where('is_system', 0)
                    ->update(['sort' => $item['sort']]);
            }

            // 记录日志
            UserLog::record($userId, 'update_category', '调整分类排序');

            return success(null, '排序成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 禁用/启用分类
     */
    public function toggleActive(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $categoryId = $request->param('id');

            if (empty($categoryId)) {
                return error('分类ID不能为空');
            }

            $category = CategoryModel::where('id', $categoryId)
                ->where('user_id', $userId)
                ->where('is_system', 0)
                ->find();

            if (!$category) {
                return error('分类不存在或不能操作');
            }

            $category->is_active = !$category->is_active;
            $category->save();

            $status = $category->is_active ? '启用' : '禁用';
            UserLog::record($userId, 'update_category', "{$status}分类: {$category->name}", 'category', $category->id);

            return success($category, '操作成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 复制系统分类
     */
    public function copySystemCategories(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            // 检查用户是否已有自定义分类
            $userCategories = CategoryModel::getUserCustomCategories($userId);
            if (!$userCategories->isEmpty()) {
                return error('您已有自定义分类，无需复制');
            }

            CategoryModel::copySystemCategoriesToUser($userId);

            // 记录日志
            UserLog::record($userId, 'create_category', '复制系统分类模板');

            return success(null, '复制成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取分类统计信息
     */
    public function stats(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $categories = CategoryModel::getUserCategories($userId);
            $stats = [];

            foreach ($categories as $category) {
                $stats[] = [
                    'id' => $category->id,
                    'name' => $category->name,
                    'icon' => $category->icon,
                    'color' => $category->color,
                    'account_count' => $category->account_count,
                    'is_system' => $category->is_system,
                ];
            }

            return success($stats, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }
}